package com.kzd.sdk.callback;

import com.google.gson.Gson;
import com.kzd.sdk.entity.KZD_BaseResponse;
import com.kzd.sdk.error.KZD_CustomException;
import com.kzd.sdk.utils.ExceptionUtils;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import okhttp3.ResponseBody;

public abstract class KZD_JsonCallback extends AbsCallback<KZD_BaseResponse> {

    @Override
    public KZD_BaseResponse convertResponse(okhttp3.Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body == null)
            throw new KZD_CustomException("body is null",1000);
        String bodyStr = body.string();
        if (bodyStr == null || bodyStr.length() == 0)
            throw new KZD_CustomException("body is null",1000);
        KZD_BaseResponse baseResponse = new Gson().fromJson(bodyStr, KZD_BaseResponse.class);
        if (baseResponse.getCode() != 1) {
            throw new KZD_CustomException(baseResponse.getMessage(),baseResponse.getCode());
        }
        return baseResponse;
    }

    @Override
    public void onStart(Request<KZD_BaseResponse, ? extends Request> request) {
        super.onStart(request);
        onStart();
    }

    @Override
    public void onSuccess(Response<KZD_BaseResponse> response) {
        onSuccess(response.body().getMessage());
    }

    @Override
    public void onError(Response<KZD_BaseResponse> response) {
        super.onError(response);
        onError(ExceptionUtils.getMessage(response.getException()));
    }

    public void onStart() {
    }

    public void onSuccess(String data) {
    }

    public void onError(String message) {
    }
}
